<?php
/**
 * @file
 * Utility PHP functions.
 *
 * Usage:
 *  - A page that wants to use the utility functions defined in this file should
 *    include/require this page once and only once.
 *
 * Parameter(s):
 *  - None.
 *
 * Global variable(s) set:
 *  - None.
 *
 * Global variable(s) unset:
 *  - None.
 *
 * Exception(s):
 *  - None.
 *
 * This file includes/requires:
 *  - None.
 */

// implementation ==============================================================
/**
 * Makes URL(s) in a text clickable.
 *
 * @param $text
 *    The text to parse.
 * @return
 *    The text formatted with HTML hyperlinks.
 */
function util_makeClickable($text) {
  // remove final '.' so that it does not become part of the URL.
  // TODO: This is a hack. Should update regular expression to not match the
  //       final '.'.
  $removedChar = "";
  $indexEnd   = strlen($text) - 1;
  if ('.' == $text[$indexEnd]) {
    // remove final '.'.
    $removedChar = $text[$indexEnd];
    $text        = substr($text, 0, $indexEnd);
  }
  $ret = ' ' . $text;
  $ret = preg_replace(
    "#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t<]*)#ise",
    "'\\1<a href=\"\\2\" target=\"_blank\">\\2</a>'",
    $ret
  );
  $ret = preg_replace(
    "#(^|[\n ])((www|ftp)\.[^ \"\t\n\r<]*)#ise",
    "'\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>'",
    $ret
  );
  $ret = preg_replace(
    "#(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i",
    "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>",
    $ret
  );
  $ret = substr($ret, 1) . $removedChar;
  return($ret);
}
?>
